import type { KnowledgeDetail } from '@/types/knowledge';

/**
 * 高级特性知识点数据
 */
export const advancedKnowledge : KnowledgeDetail[] = [
	{
		id: 16,
		title: '多线程编程',
		description: '线程创建、同步机制、线程池，掌握Java并发编程核心技术，提升程序性能。',
		icon: '⚙️',
		categoryId: 'advanced',
		categoryName: '高级特性',
		categoryIcon: '🚀',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #9b59b6 0%, #8e44ad 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: '线程创建有两种方式：继承Thread类和实现Runnable接口，推荐使用Runnable实现线程复用。',
				code: `// 方式1：继承Thread类
public class MyThread extends Thread {
    @Override
    public void run() {
        System.out.println("Thread: " + getName() + " running");
    }
}

// 使用
MyThread thread = new MyThread();
thread.start();

// 方式2：实现Runnable接口（推荐）
public class MyRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("Runnable running");
    }
}

// 使用
Thread thread = new Thread(new MyRunnable());
thread.start();

// 方式3：Lambda表达式（Java 8+）
Thread thread = new Thread(() -> {
    System.out.println("Lambda thread running");
});
thread.start();`
			},
			{
				point: '线程同步使用synchronized关键字或Lock接口，防止多个线程同时访问共享资源导致数据不一致。',
				code: `// synchronized方法
public class Counter {
    private int count = 0;
    
    // 同步方法
    public synchronized void increment() {
        count++;
    }
    
    // 同步代码块
    public void decrement() {
        synchronized (this) {
            count--;
        }
    }
}

// Lock接口（更灵活）
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockCounter {
    private int count = 0;
    private Lock lock = new ReentrantLock();
    
    public void increment() {
        lock.lock();
        try {
            count++;
        } finally {
            lock.unlock();  // 确保释放锁
        }
    }
}`
			},
			{
				point: '线程通信使用wait()、notify()、notifyAll()方法，必须在synchronized代码块中调用。',
				code: `public class ProducerConsumer {
    private Queue<Integer> queue = new LinkedList<>();
    private int capacity = 5;
    
    // 生产者
    public synchronized void produce() throws InterruptedException {
        while (queue.size() == capacity) {
            wait();  // 队列满，等待
        }
        
        int value = new Random().nextInt(100);
        queue.add(value);
        System.out.println("生产: " + value);
        
        notifyAll();  // 唤醒消费者
    }
    
    // 消费者
    public synchronized void consume() throws InterruptedException {
        while (queue.isEmpty()) {
            wait();  // 队列空，等待
        }
        
        int value = queue.remove();
        System.out.println("消费: " + value);
        
        notifyAll();  // 唤醒生产者
    }
}`
			},
			{
				point: '线程池使用ExecutorService管理线程，避免频繁创建销毁线程的开销，提高性能。',
				code: `import java.util.concurrent.*;

public class ThreadPoolDemo {
    public static void main(String[] args) {
        // 固定大小线程池
        ExecutorService fixedPool = Executors.newFixedThreadPool(5);
        
        // 提交任务
        for (int i = 0; i < 10; i++) {
            int taskId = i;
            fixedPool.submit(() -> {
                System.out.println("Task " + taskId + " executed by " 
                    + Thread.currentThread().getName());
            });
        }
        
        // 关闭线程池
        fixedPool.shutdown();
        
        // 自定义线程池
        ThreadPoolExecutor customPool = new ThreadPoolExecutor(
            2,  // 核心线程数
            5,  // 最大线程数
            60, TimeUnit.SECONDS,  // 空闲线程存活时间
            new LinkedBlockingQueue<>(10),  // 任务队列
            new ThreadPoolExecutor.CallerRunsPolicy()  // 拒绝策略
        );
        
        customPool.execute(() -> System.out.println("Custom task"));
        customPool.shutdown();
    }
}`
			},
			{
				point: '并发工具类如CountDownLatch、CyclicBarrier、Semaphore帮助控制线程协作和资源访问。',
				code: `import java.util.concurrent.*;

public class ConcurrentUtils {
    // CountDownLatch：等待多个线程完成
    public void countDownLatchDemo() throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);
        
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                System.out.println("Worker finished");
                latch.countDown();
            }).start();
        }
        
        latch.await();  // 等待所有线程完成
        System.out.println("All workers finished");
    }
    
    // CyclicBarrier：多个线程互相等待
    public void cyclicBarrierDemo() {
        CyclicBarrier barrier = new CyclicBarrier(3, () -> {
            System.out.println("All threads reached barrier");
        });
        
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                try {
                    System.out.println("Thread waiting");
                    barrier.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
    
    // Semaphore：控制同时访问资源的线程数
    public void semaphoreDemo() {
        Semaphore semaphore = new Semaphore(2);  // 最多2个线程
        
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println("Thread acquired");
                    Thread.sleep(1000);
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}`
			}
		]
	},
	{
		id: 17,
		title: '反射机制',
		description: '运行时动态获取类信息、调用方法、访问字段，是框架开发的基础技术。',
		icon: '🔍',
		categoryId: 'advanced',
		categoryName: '高级特性',
		categoryIcon: '🚀',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #9b59b6 0%, #8e44ad 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: '获取Class对象的三种方式：类名.class、对象.getClass()、Class.forName()。',
				code: `public class ReflectionDemo {
    public static void main(String[] args) throws ClassNotFoundException {
        // 方式1：通过类名.class
        Class<String> clazz1 = String.class;
        
        // 方式2：通过对象.getClass()
        String str = "Hello";
        Class<?> clazz2 = str.getClass();
        
        // 方式3：通过Class.forName()
        Class<?> clazz3 = Class.forName("java.lang.String");
        
        // 判断是否同一个Class对象
        System.out.println(clazz1 == clazz2);  // true
        System.out.println(clazz2 == clazz3);  // true
        
        // 获取类信息
        System.out.println("类名: " + clazz1.getName());
        System.out.println("简单类名: " + clazz1.getSimpleName());
        System.out.println("包名: " + clazz1.getPackage());
    }
}`
			},
			{
				point: '通过反射创建对象、调用方法、访问字段，实现动态编程。',
				code: `import java.lang.reflect.*;

public class Person {
    private String name;
    private int age;
    
    public Person() {}
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    private void privateMethod() {
        System.out.println("Private method");
    }
}

public class ReflectionOperations {
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Person.class;
        
        // 创建对象
        Person person1 = (Person) clazz.newInstance();  // 已过时
        Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
        Person person2 = (Person) constructor.newInstance("张三", 25);
        
        // 访问字段
        Field nameField = clazz.getDeclaredField("name");
        nameField.setAccessible(true);  // 访问私有字段
        nameField.set(person2, "李四");
        System.out.println(nameField.get(person2));
        
        // 调用方法
        Method method = clazz.getDeclaredMethod("privateMethod");
        method.setAccessible(true);
        method.invoke(person2);
    }
}`
			},
			{
				point: '反射可以获取类的所有信息：字段、方法、构造器、注解等。',
				code: `public class ClassAnalyzer {
    public static void analyzeClass(Class<?> clazz) {
        System.out.println("=== 类分析: " + clazz.getName() + " ===\n");
        
        // 获取所有字段
        System.out.println("字段:");
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            System.out.println("  " + Modifier.toString(field.getModifiers()) 
                + " " + field.getType().getSimpleName() 
                + " " + field.getName());
        }
        
        // 获取所有方法
        System.out.println("\n方法:");
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println("  " + method.getReturnType().getSimpleName() 
                + " " + method.getName() + "()");
        }
        
        // 获取所有构造器
        System.out.println("\n构造器:");
        Constructor<?>[] constructors = clazz.getDeclaredConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println("  " + constructor.getName());
        }
        
        // 获取注解
        System.out.println("\n注解:");
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println("  " + annotation);
        }
    }
}`
			},
			{
				point: '反射性能较低，应避免在性能敏感的代码中频繁使用，可以通过缓存Class对象优化。',
				code: `import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ReflectionPerformance {
    // 缓存Class对象
    private static Map<String, Class<?>> classCache = new HashMap<>();
    
    public static Class<?> getClass(String className) throws ClassNotFoundException {
        if (!classCache.containsKey(className)) {
            classCache.put(className, Class.forName(className));
        }
        return classCache.get(className);
    }
    
    // 性能测试
    public static void main(String[] args) throws Exception {
        // 直接调用
        long start = System.nanoTime();
        for (int i = 0; i < 10000; i++) {
            String str = "Hello";
            str.length();
        }
        long direct = System.nanoTime() - start;
        
        // 反射调用
        start = System.nanoTime();
        Method method = String.class.getMethod("length");
        String str = "Hello";
        for (int i = 0; i < 10000; i++) {
            method.invoke(str);
        }
        long reflect = System.nanoTime() - start;
        
        System.out.println("直接调用: " + direct + " ns");
        System.out.println("反射调用: " + reflect + " ns");
        System.out.println("反射慢 " + (reflect / direct) + " 倍");
    }
}`
			},
			{
				point: '反射常用于框架开发、依赖注入、动态代理等场景，是Spring等框架的核心技术。',
				code: `import java.lang.annotation.*;
import java.lang.reflect.*;

// 自定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Autowired {
}

// 简单的依赖注入容器
public class SimpleContainer {
    private Map<Class<?>, Object> beans = new HashMap<>();
    
    // 注册Bean
    public void register(Class<?> clazz) throws Exception {
        Object instance = clazz.newInstance();
        beans.put(clazz, instance);
        
        // 注入依赖
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(Autowired.class)) {
                field.setAccessible(true);
                Object dependency = beans.get(field.getType());
                if (dependency != null) {
                    field.set(instance, dependency);
                }
            }
        }
    }
    
    // 获取Bean
    public <T> T getBean(Class<T> clazz) {
        return (T) beans.get(clazz);
    }
}

// 使用示例
class UserService {
    @Autowired
    private UserDao userDao;
    
    public void saveUser() {
        userDao.save();
    }
}

class UserDao {
    public void save() {
        System.out.println("保存用户");
    }
}`
			}
		]
	},
	{
		id: 18,
		title: '注解',
		description: '元数据标记，框架配置，编译检查，Java注解是框架和工具的重要基础。',
		icon: '@',
		categoryId: 'advanced',
		categoryName: '高级特性',
		categoryIcon: '🚀',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #9b59b6 0%, #8e44ad 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: 'Java内置注解：@Override、@Deprecated、@SuppressWarnings等，用于编译期检查。',
				code: `public class BuiltInAnnotations {
    // @Override：检查是否正确重写父类方法
    @Override
    public String toString() {
        return "BuiltInAnnotations";
    }
    
    // @Deprecated：标记过时的方法
    @Deprecated
    public void oldMethod() {
        System.out.println("此方法已过时");
    }
    
    // @SuppressWarnings：抑制警告
    @SuppressWarnings("unchecked")
    public void suppressWarning() {
        List list = new ArrayList();
        list.add("item");
    }
    
    // @FunctionalInterface：标记函数式接口
    @FunctionalInterface
    interface MyFunction {
        void execute();
    }
    
    // @SafeVarargs：抑制泛型可变参数警告
    @SafeVarargs
    public final <T> void safeMethod(T... args) {
        for (T arg : args) {
            System.out.println(arg);
        }
    }
}`
			},
			{
				point: '自定义注解使用@interface定义，通过元注解@Retention、@Target、@Documented等配置。',
				code: `import java.lang.annotation.*;

// 定义自定义注解
@Retention(RetentionPolicy.RUNTIME)  // 运行时保留
@Target({ElementType.TYPE, ElementType.METHOD})  // 可用于类和方法
@Documented  // 包含在JavaDoc中
@Inherited  // 可继承
public @interface MyAnnotation {
    // 注解属性
    String value() default "";  // 默认值
    int priority() default 0;
    String[] tags() default {};
}

// 使用自定义注解
@MyAnnotation(value = "类注解", priority = 1, tags = {"tag1", "tag2"})
public class AnnotatedClass {
    
    @MyAnnotation("方法注解")
    public void annotatedMethod() {
        System.out.println("带注解的方法");
    }
}

// 复杂注解示例
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {
    String name();  // 必填
    String type() default "VARCHAR";
    int length() default 255;
    boolean nullable() default true;
}`
			},
			{
				point: '通过反射读取注解信息，实现基于注解的配置和处理。',
				code: `import java.lang.reflect.*;

public class AnnotationProcessor {
    public static void processAnnotations(Class<?> clazz) {
        // 处理类注解
        if (clazz.isAnnotationPresent(MyAnnotation.class)) {
            MyAnnotation annotation = clazz.getAnnotation(MyAnnotation.class);
            System.out.println("类注解值: " + annotation.value());
            System.out.println("优先级: " + annotation.priority());
            System.out.println("标签: " + Arrays.toString(annotation.tags()));
        }
        
        // 处理方法注解
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.isAnnotationPresent(MyAnnotation.class)) {
                MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
                System.out.println("方法 " + method.getName() 
                    + " 注解值: " + annotation.value());
            }
        }
        
        // 处理字段注解
        for (Field field : clazz.getDeclaredFields()) {
            if (field.isAnnotationPresent(Column.class)) {
                Column column = field.getAnnotation(Column.class);
                System.out.println("字段 " + field.getName() 
                    + " 映射到列: " + column.name());
            }
        }
    }
}`
			},
			{
				point: '注解处理器可以在编译期处理注解，生成代码或验证规则，如Lombok使用注解处理器生成代码。',
				code: `import javax.annotation.processing.*;
import javax.lang.model.element.*;
import java.util.Set;

// 编译期注解处理器
@SupportedAnnotationTypes("com.example.MyAnnotation")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class MyAnnotationProcessor extends AbstractProcessor {
    
    @Override
    public boolean process(Set<? extends TypeElement> annotations, 
                          RoundEnvironment roundEnv) {
        // 获取所有被@MyAnnotation标注的元素
        for (Element element : roundEnv.getElementsAnnotatedWith(MyAnnotation.class)) {
            // 处理注解
            MyAnnotation annotation = element.getAnnotation(MyAnnotation.class);
            String value = annotation.value();
            
            // 生成代码或验证
            processingEnv.getMessager().printMessage(
                Diagnostic.Kind.NOTE,
                "处理注解: " + value,
                element
            );
        }
        return true;
    }
}

// 配置文件 META-INF/services/javax.annotation.processing.Processor
// com.example.MyAnnotationProcessor`
			},
			{
				point: '注解在框架中广泛应用，如Spring的@Autowired、@Controller，JPA的@Entity、@Table等。',
				code: `// Spring框架注解示例
import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;

@Controller  // 控制器组件
@RequestMapping("/user")
public class UserController {
    
    @Autowired  // 依赖注入
    private UserService userService;
    
    @GetMapping("/{id}")  // 映射GET请求
    public User getUser(@PathVariable Long id) {
        return userService.findById(id);
    }
}

// JPA注解示例
import javax.persistence.*;

@Entity  // 实体类
@Table(name = "users")  // 表名
public class User {
    
    @Id  // 主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @Column(name = "user_name", length = 50, nullable = false)
    private String userName;
    
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private List<Order> orders;
}

// 验证注解示例
import javax.validation.constraints.*;

public class UserDTO {
    @NotNull(message = "用户名不能为空")
    @Size(min = 3, max = 20, message = "用户名长度3-20")
    private String username;
    
    @Email(message = "邮箱格式不正确")
    private String email;
    
    @Min(value = 18, message = "年龄不能小于18")
    @Max(value = 100, message = "年龄不能大于100")
    private Integer age;
}`
			}
		]
	},
	{
		id: 19,
		title: '泛型',
		description: '类型参数化，编译期类型检查，避免类型转换，提高代码安全性和可读性。',
		icon: '<T>',
		categoryId: 'advanced',
		categoryName: '高级特性',
		categoryIcon: '🚀',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #9b59b6 0%, #8e44ad 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: '泛型类、泛型接口、泛型方法的定义和使用，实现代码复用和类型安全。',
				code: `// 泛型类
public class Box<T> {
    private T value;
    
    public void set(T value) {
        this.value = value;
    }
    
    public T get() {
        return value;
    }
}

// 使用泛型类
Box<String> stringBox = new Box<>();
stringBox.set("Hello");
String value = stringBox.get();  // 无需类型转换

// 泛型接口
public interface Comparable<T> {
    int compareTo(T other);
}

// 实现泛型接口
public class Student implements Comparable<Student> {
    private int score;
    
    @Override
    public int compareTo(Student other) {
        return this.score - other.score;
    }
}

// 泛型方法
public class GenericMethod {
    public static <T> T getMiddle(T... array) {
        return array[array.length / 2];
    }
    
    // 使用
    String middle = getMiddle("a", "b", "c");  // 返回"b"
    Integer num = getMiddle(1, 2, 3);  // 返回2
}`
			},
			{
				point: '泛型通配符：? 表示未知类型，? extends T 上界通配符，? super T 下界通配符。',
				code: `import java.util.*;

public class WildcardDemo {
    // 无界通配符
    public void printList(List<?> list) {
        for (Object item : list) {
            System.out.println(item);
        }
    }
    
    // 上界通配符（只能读取）
    public double sumNumbers(List<? extends Number> list) {
        double sum = 0;
        for (Number num : list) {
            sum += num.doubleValue();
        }
        return sum;
    }
    
    // 下界通配符（只能写入）
    public void addNumbers(List<? super Integer> list) {
        list.add(1);
        list.add(2);
        list.add(3);
    }
    
    public static void main(String[] args) {
        WildcardDemo demo = new WildcardDemo();
        
        // 上界通配符
        List<Integer> integers = Arrays.asList(1, 2, 3);
        List<Double> doubles = Arrays.asList(1.1, 2.2, 3.3);
        demo.sumNumbers(integers);  // OK
        demo.sumNumbers(doubles);   // OK
        
        // 下界通配符
        List<Number> numbers = new ArrayList<>();
        demo.addNumbers(numbers);   // OK
    }
}`
			},
			{
				point: '类型擦除：Java泛型在编译后会被擦除为原始类型，运行时无法获取泛型信息。',
				code: `public class TypeErasureDemo {
    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>();
        List<Integer> intList = new ArrayList<>();
        
        // 运行时类型相同（都是ArrayList）
        System.out.println(stringList.getClass() == intList.getClass());  // true
        
        // 类型擦除导致的问题
        List list = new ArrayList<String>();
        list.add("String");
        list.add(123);  // 编译警告，运行时OK（类型擦除）
        
        // 无法创建泛型数组
        // List<String>[] array = new List<String>[10];  // 编译错误
        
        // 无法使用instanceof检查泛型类型
        // if (stringList instanceof List<String>) { }  // 编译错误
    }
    
    // 泛型方法的类型擦除
    public <T> void print(T value) {
        // T被擦除为Object
        System.out.println(value);
    }
    
    // 有界泛型的类型擦除
    public <T extends Number> void printNumber(T num) {
        // T被擦除为Number
        System.out.println(num.doubleValue());
    }
}`
			},
			{
				point: '泛型约束：使用extends关键字限制类型参数，可以调用约束类型的方法。',
				code: `// 单个约束
public class NumberBox<T extends Number> {
    private T value;
    
    public void setValue(T value) {
        this.value = value;
    }
    
    public double getDoubleValue() {
        return value.doubleValue();  // 可以调用Number的方法
    }
}

// 多个约束（接口）
public class ComparableBox<T extends Comparable<T> & Serializable> {
    private T value;
    
    public int compare(T other) {
        return value.compareTo(other);  // 可以调用Comparable方法
    }
}

// 使用约束泛型
public class GenericConstraints {
    // 查找最大值
    public static <T extends Comparable<T>> T max(T a, T b) {
        return a.compareTo(b) > 0 ? a : b;
    }
    
    // 使用
    public static void main(String[] args) {
        Integer maxInt = max(10, 20);  // 20
        String maxStr = max("apple", "banana");  // "banana"
        
        // NumberBox只能存储Number及其子类
        NumberBox<Integer> intBox = new NumberBox<>();
        NumberBox<Double> doubleBox = new NumberBox<>();
        // NumberBox<String> stringBox = new NumberBox<>();  // 编译错误
    }
}`
			},
			{
				point: '泛型最佳实践：优先使用泛型而不是原始类型，注意类型安全，避免类型转换异常。',
				code: `public class GenericBestPractices {
    // ❌ 不推荐：使用原始类型
    public void badPractice() {
        List list = new ArrayList();
        list.add("String");
        list.add(123);
        String str = (String) list.get(1);  // 运行时异常！
    }
    
    // ✅ 推荐：使用泛型
    public void goodPractice() {
        List<String> list = new ArrayList<>();
        list.add("String");
        // list.add(123);  // 编译错误！
        String str = list.get(0);  // 无需类型转换
    }
    
    // ✅ 推荐：泛型工厂方法
    public static <K, V> Map<K, V> createHashMap() {
        return new HashMap<>();
    }
    
    // 使用
    Map<String, Integer> map = createHashMap();
    
    // ✅ 推荐：PECS原则（Producer Extends, Consumer Super）
    // 生产者使用extends
    public void processProducer(List<? extends Number> numbers) {
        for (Number num : numbers) {
            System.out.println(num);
        }
    }
    
    // 消费者使用super
    public void processConsumer(List<? super Integer> list) {
        list.add(1);
        list.add(2);
    }
}`
			}
		]
	},
	{
		id: 20,
		title: '网络编程',
		description: 'Socket编程、HTTP客户端、网络协议，掌握Java网络编程实现网络通信。',
		icon: '🌐',
		categoryId: 'advanced',
		categoryName: '高级特性',
		categoryIcon: '🚀',
		difficulty: '进阶',
		color: 'linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%)',
		headerBg: 'linear-gradient(135deg, #2c3e50 0%, #34495e 100%)',
		tagBg: 'linear-gradient(135deg, #9b59b6 0%, #8e44ad 100%)',
		tagColor: '#ffffff',
		difficultyBg: 'linear-gradient(135deg, #e74c3c 0%, #c0392b 100%)',
		keyPoints: [
			{
				point: 'TCP Socket编程使用ServerSocket和Socket实现服务端和客户端通信。',
				code: `import java.io.*;
import java.net.*;

// TCP服务端
public class TCPServer {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("服务器启动，监听端口8080");
        
        while (true) {
            Socket socket = serverSocket.accept();
            System.out.println("客户端连接: " + socket.getRemoteSocketAddress());
            
            // 处理客户端请求
            new Thread(() -> {
                try {
                    BufferedReader in = new BufferedReader(
                        new InputStreamReader(socket.getInputStream()));
                    PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
                    
                    String message = in.readLine();
                    System.out.println("收到消息: " + message);
                    out.println("Echo: " + message);
                    
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

// TCP客户端
public class TCPClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 8080);
        
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(
            new InputStreamReader(socket.getInputStream()));
        
        out.println("Hello Server");
        String response = in.readLine();
        System.out.println("服务器响应: " + response);
        
        socket.close();
    }
}`
			},
			{
				point: 'UDP Socket使用DatagramSocket和DatagramPacket实现无连接通信，适用于实时数据传输。',
				code: `import java.net.*;

// UDP服务端
public class UDPServer {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket(9090);
        byte[] buffer = new byte[1024];
        
        System.out.println("UDP服务器启动，监听端口9090");
        
        while (true) {
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            socket.receive(packet);  // 接收数据
            
            String message = new String(packet.getData(), 0, packet.getLength());
            System.out.println("收到消息: " + message);
            
            // 响应客户端
            String response = "Echo: " + message;
            byte[] responseData = response.getBytes();
            DatagramPacket responsePacket = new DatagramPacket(
                responseData, 
                responseData.length,
                packet.getAddress(),
                packet.getPort()
            );
            socket.send(responsePacket);
        }
    }
}

// UDP客户端
public class UDPClient {
    public static void main(String[] args) throws Exception {
        DatagramSocket socket = new DatagramSocket();
        
        String message = "Hello UDP Server";
        byte[] data = message.getBytes();
        
        InetAddress address = InetAddress.getByName("localhost");
        DatagramPacket packet = new DatagramPacket(data, data.length, address, 9090);
        socket.send(packet);
        
        // 接收响应
        byte[] buffer = new byte[1024];
        DatagramPacket responsePacket = new DatagramPacket(buffer, buffer.length);
        socket.receive(responsePacket);
        
        String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
        System.out.println("服务器响应: " + response);
        
        socket.close();
    }
}`
			},
			{
				point: 'HTTP客户端使用HttpURLConnection或HttpClient发送HTTP请求。',
				code: `import java.io.*;
import java.net.*;

// HttpURLConnection示例
public class HttpURLConnectionDemo {
    public static String get(String urlString) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        
        int responseCode = connection.getResponseCode();
        if (responseCode == 200) {
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            return response.toString();
        }
        return null;
    }
    
    public static String post(String urlString, String data) throws IOException {
        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        
        OutputStream os = connection.getOutputStream();
        os.write(data.getBytes());
        os.flush();
        os.close();
        
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(connection.getInputStream()));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        return response.toString();
    }
}`
			},
			{
				point: 'NIO网络编程使用Selector、Channel、Buffer实现非阻塞IO，提高并发性能。',
				code: `import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;

// NIO服务端
public class NIOServer {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.bind(new InetSocketAddress(8080));
        serverChannel.configureBlocking(false);
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        
        System.out.println("NIO服务器启动");
        
        while (true) {
            selector.select();  // 阻塞等待事件
            
            Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
            while (keys.hasNext()) {
                SelectionKey key = keys.next();
                keys.remove();
                
                if (key.isAcceptable()) {
                    // 接受连接
                    SocketChannel client = serverChannel.accept();
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    // 读取数据
                    SocketChannel client = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int read = client.read(buffer);
                    
                    if (read > 0) {
                        buffer.flip();
                        byte[] data = new byte[buffer.remaining()];
                        buffer.get(data);
                        System.out.println("收到: " + new String(data));
                        
                        // 响应
                        buffer.clear();
                        buffer.put("Echo".getBytes());
                        buffer.flip();
                        client.write(buffer);
                    }
                }
            }
        }
    }
}`
			},
			{
				point: 'URL和URLConnection类提供高级HTTP操作，支持各种HTTP方法和请求头设置。',
				code: `import java.net.*;
import java.io.*;

public class URLDemo {
    public static void main(String[] args) throws Exception {
        // URL解析
        URL url = new URL("https://api.example.com/users?id=123#section");
        System.out.println("协议: " + url.getProtocol());
        System.out.println("主机: " + url.getHost());
        System.out.println("端口: " + url.getPort());
        System.out.println("路径: " + url.getPath());
        System.out.println("查询: " + url.getQuery());
        System.out.println("锚点: " + url.getRef());
        
        // URLConnection高级操作
        URLConnection connection = url.openConnection();
        
        // 设置请求头
        connection.setRequestProperty("User-Agent", "MyApp/1.0");
        connection.setRequestProperty("Accept", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        
        // 获取响应头
        Map<String, List<String>> headers = connection.getHeaderFields();
        for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
        
        // 读取内容
        InputStream is = connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    }
}`
			}
		]
	}
];